package com.winding.plugin.swagger.entity;

import io.swagger.models.Path;
import io.swagger.models.Swagger;
import io.swagger.models.Tag;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.stream.Collectors;

import static java.util.function.UnaryOperator.identity;

/**
 *
 * @author wind
 * @version 1.0
 * @since 2018/12/5
 */
@Slf4j
public class WrapSwagger extends Swagger {
    /**
     * tag存储的所有的path
     */
    @Getter
    @Setter
    private Map<Tag, List<PathOperation>> tagPath = new HashMap<>();


    public void process() {
        Optional.ofNullable(getTags()).ifPresent(p -> {
            Map<String, Tag> tagMap = p.stream()
                    .collect(Collectors.toMap(Tag::getName, identity(),
                            (existingValue, newValue) -> existingValue));
            Optional.ofNullable(getPaths()).ifPresent(t ->
                    t.forEach((k, v) -> processPath(k, v, tagMap))
            );
        });


    }

    public void processPath(String k, Path v, Map<String, Tag> tagMap) {
        Optional.ofNullable(v.getOperations()).ifPresent(operations ->
                operations.forEach(operation ->
                        Optional.ofNullable(operation.getTags()).ifPresent(tagsList ->
                                tagsList.forEach(s -> {
                                    Tag tag = tagMap.get(s);
                                    if (tag != null) {
                                        List<PathOperation> mapList = tagPath.get(tag);
                                        if (mapList == null) {
                                            mapList = new ArrayList<>();
                                        }
                                        PathOperation pathOperation = new PathOperation();
                                        pathOperation.setHrefPath(k.replace("/", ""));
                                        pathOperation.setRealPath(k);
                                        pathOperation.setOperation(operation);
                                        mapList.add(pathOperation);
                                        tagPath.put(tag, mapList);
                                    }
                                })
                        )
                )
        );
    }

}
